uniform sampler2D NormalMap;
uniform samplerCube EnvironmentMap;

varying mat3 rotMatrix; // first row of the 3x3 transform from tangent to cube space
varying vec2 bumpCoord0;
varying vec2 bumpCoord1;
varying vec2 bumpCoord2;
varying vec3 eyeVector;
varying vec3 lightVec;


void main(void)
{
	vec4 deepColor = vec4(0, 0.3, 0.5, 1.0);
	vec4 shallowColor = vec4(0, 1, 1, 1.0);
	vec4 reflectionColor = vec4(0.95, 1, 1, 1.0);
	float reflectionAmount = 0.9;
	float reflectionBlur = 0.0;
	float waterAmount = 0.35;
	float fresnelPower = 5.0;
	float fresnelBias = 0.328;
	float hdrMultiplier = 0.471;
	
    vec4 t0 = texture2D(NormalMap, bumpCoord0) * 2.0 - 1.0;
    vec4 t1 = texture2D(NormalMap, bumpCoord1) * 2.0 - 1.0;
    vec4 t2 = texture2D(NormalMap, bumpCoord2) * 2.0 - 1.0;
    vec3 N = t0.xyz + t1.xyz + t2.xyz;

    N = normalize(rotMatrix * N);

    vec3 E = normalize(eyeVector);
    vec3 R = reflect(E, N);

    R.z = -R.z;

    vec4 reflection = vec4(0.2*dot(N, lightVec),0.2*dot(N, lightVec),0.2*dot(N, lightVec),0.9);

    reflection.rgb *= (reflection.r + reflection.g + reflection.b) * hdrMultiplier;

    float facing = 1.0 - dot(-E, N);
    float fresnel = clamp(fresnelBias + pow(facing, fresnelPower), 0.0, 1.0);

    vec4 waterColor = mix(shallowColor, deepColor, facing) * waterAmount;

    reflection = mix(waterColor,  reflection * reflectionColor, fresnel) * reflectionAmount;
    gl_FragColor = waterColor + reflection;
}